package com.mzpai.web.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.gexin.fastjson.JSONArray;
import com.mzpai.product.model.StoreCategory;
import com.mzpai.product.model.SystemConfig;
import com.mzpai.product.service.StoreCategoryService;
import com.mzpai.product.service.SystemConfigService;
import com.mzpai.util.DateUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
 *
 * <b>商品分类 | Controller</b><br>
 *
 * yanglijun 2021-03-16 18:45:40
 * 
 *  @version 1.0.0
 */
@Api(value = "商品分类查询")
@RestController
@RequestMapping("/storeCategory")
public class StoreCategoryController extends BaseController {

	@Autowired 
	private StoreCategoryService storeCategoryService;
	
	@Autowired 
	private SystemConfigService systemConfigService;
	
	private static Logger log = LoggerFactory.getLogger(StoreCategoryController.class);
	/** 
	*
	* 查询列表 
	* @throws Exception
	*/
	@RequestMapping("/getList")
	@ApiOperation(value = "查询门店下商品库数据分类接口；storeId = 0 代表平台; parentId 可为空，如果不是空，只查询当前id下子数据")
	public ResponseVo<JSONArray> getList(@RequestParam(value = "storeId", required = true) String storeId,
			@RequestParam(value = "parentId", required = false) String parentId) throws Exception {
		ResponseVo<JSONArray> res=new ResponseVo<JSONArray>();
		try{
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("storeId", storeId);
			if(StringUtils.isNoneBlank(parentId)) {
				map.put("pid", parentId);
			}
			map.put("isShow", "1");
			List<StoreCategory> list = storeCategoryService.getList(map);
			JSONArray arr = getDateString(list, parentId);
			res.setResult(arr);
			return res;
		} catch(Exception e) {
			res.setCode(-1);
			logger.error("msg1=获取分类信息失败,{}", e);
		}
		return res;
	}
	
	
	/** 
	*
	* 查询列表 
	* @throws Exception
	*/
	@RequestMapping("/save")
	@ApiOperation(value = "保存门店分类信息")
	public ResponseVo<StoreCategory> save(@RequestParam(value = "storeCategory", required = true) String storeCategory) throws Exception {
		ResponseVo<StoreCategory> res=new ResponseVo<StoreCategory>();
		try{
			log.info("msg=对象信息={}", storeCategory );
			StoreCategory o = JSONObject.parseObject(storeCategory, StoreCategory.class);
			String cateName=o.getCateName();
			
			if(!StringUtils.isNullOrBlank(cateName)){
				/**检查商品名称是否包含禁用关键字*/
				String keyWords = checkKeyWord(cateName);
				if(StringUtils.isNoneBlank(keyWords)) {
					res.setCode(-1);
					res.setMessage("分类名称存在关键字[" + StringUtils.unicodeToString(keyWords) + "]");
					return res;
				}
			}
			
			if(o.getId() == null){
				o.setAddTime(DateUtil.getUTCTime(null).intValue());
				o.setSort(1);
				o.setCateCode(StringUtils.getRandomCode(8));
				o.setPic("");
				//设置full_cate_code
				addFullCateCode(o, "add");
				int id = storeCategoryService.save(o);
				o.setId(id);
			} else {
				//设置full_cate_code
				addFullCateCode(o, "update");
				storeCategoryService.update(o);
				o = storeCategoryService.queryById(o.getId() + "");
			}
			res.setResult(o);
			return res;
		} catch(Exception e) {
			res.setCode(-1);
			logger.error("msg1=获取分类信息失败,{}", e);
		}
		return res;
	}
	
	/**
	 * 查询商品是否关键字， 获取配置
	 * @param cateName
	 * @return
	 */
	private String checkKeyWord(String cateName) {
		String str = null;
		SystemConfig systemConfig = systemConfigService.getConfigByKey("disabled_keys");
		if(systemConfig != null) {
			String smp = systemConfig.getValue().replace("\"", "");
			for(String key : smp.split(",")) {
				if(cateName.indexOf(StringUtils.unicodeToString(key)) >= 0) {
					str = key;
					break;
				}
			}
		}
		return str;
	}
	
	
	/***
	 * 设置 全分类编码格式 WEFIN001-MPFINFOT-MMMUUUOO; WEFIN001是顶层;MPFINFOT:第二层；MMMUUUOO:第三层
	 * @param o
	 * 
	 * type :  add,  update
	 */
	private void addFullCateCode(StoreCategory o, String type) {
		if("update".equals(type)) {
			StoreCategory old = storeCategoryService.queryById(o.getId() + "");
				o.setFullCateCode(o.getPid() == 0 ? old.getCateCode() : (storeCategoryService.queryById(o.getPid() + "").getFullCateCode() + "-" + old.getCateCode()));
		} else {
			o.setFullCateCode(o.getPid() == 0 ? o.getCateCode() : (storeCategoryService.queryById(o.getPid() + "").getFullCateCode() + "-" + o.getCateCode()));
		}
	}


	/** 
	*
	* 查询列表 
	* @throws Exception
	*/
	@RequestMapping("/update")
	@ApiOperation(value = "修改门店分类信息")
	public ResponseVo<StoreCategory> update(@RequestParam(value = "storeCategory", required = true) String storeCategory) throws Exception {
		ResponseVo<StoreCategory> res=new ResponseVo<StoreCategory>();
		try{
			log.info("msg=对象信息={}", storeCategory );
			StoreCategory o = JSONObject.parseObject(storeCategory, StoreCategory.class);
			if(o.getId() == null) {
				throw new Exception("修改门店分类id为空！");
			}
			storeCategoryService.update(o);
			o = storeCategoryService.queryById(o.getId() + "");
			res.setResult(o);
			return res;
		} catch(Exception e) {
			res.setCode(-1);
			logger.error("msg1=获取分类信息失败,{}", e);
		}
		return res;
	}
	
	
	/** 
	*
	* 查询列表 
	* @throws Exception
	*/
	@RequestMapping("/queryById")
	@ApiOperation(value = "根据ID， 查询分类信息 ！")
	public ResponseVo<StoreCategory> queryById(@RequestParam(value = "id", required = true) String id) throws Exception {
		ResponseVo<StoreCategory> res=new ResponseVo<StoreCategory>();
		try{
			StoreCategory o  = storeCategoryService.queryById(id);
			res.setResult(o);
			return res;
		} catch(Exception e) {
			res.setCode(-1);
			logger.error("msg1=获取分类信息失败,{}", e);
		}
		return res;
	}
	
	
	/** 
	*
	* 保存分类顺序
	* @throws Exception
	*/
	@RequestMapping("/saveCateSort")
	@ApiOperation(value = "保存分类顺序")
	public ResponseVo<Boolean> saveCateSort(@RequestParam(value = "str", required = true) String str) throws Exception {
		ResponseVo<Boolean> res=new ResponseVo<Boolean>();
		try{
			List<StoreCategory> list = JSON.parseArray(str, StoreCategory.class);
			storeCategoryService.updateSort(list);
			res.setResult(true);
 			return res;
		} catch(Exception e) {
			res.setCode(-1);
			res.setResult(false);
			logger.error("msg1=获取分类信息失败,{}", e);
		}
		return res;
	}
	
	
	
	private JSONArray getDateString(List<StoreCategory> list, String pid) {
		JSONArray jsonArr = new JSONArray();
		String sp = StringUtils.isBlank(pid) ? "1" : "2";
		switch(sp) {
			case "1" :	
				getJsonString(list, jsonArr);
				break;
			case "2" : 
				getSimpleArr(list, jsonArr, pid);
				break;
		}
		
		return jsonArr;
	}
	
	private void getJsonString(List<StoreCategory> list, JSONArray jsonArr) {
		for(StoreCategory s : list) {
			if(s.getPid() == 0) {
				JSONObject o = new JSONObject();
				o.put("cateName", s.getCateName());
				o.put("id", s.getId());
				if("true".equals(s.getIsParent())) {
					getSecJsonString(list, s.getId(), o);
				}
				jsonArr.add(o);
			}
		}
	  }
	
	
	private void getSecJsonString(List<StoreCategory> list, Integer pid, JSONObject json) {
		JSONArray arr = new JSONArray();
		for(StoreCategory s : list) {
			if(s.getPid().intValue() == pid.intValue()) {
				JSONObject o = new JSONObject();
				o.put("cateName", s.getCateName());
				o.put("id", s.getId());
				if("true".equals(s.getIsParent())) {
					getSecJsonString(list, s.getId(), o);
				}
				arr.add(o);
			}
		}
		json.put("child", arr);
	}
	
	
	private void getSimpleArr(List<StoreCategory> list, JSONArray jsonArr, String pid) {
		for(StoreCategory s : list) {
			if(s.getPid().toString().equals(pid)) {
				JSONObject o = new JSONObject();
				o.put("cateName", s.getCateName());
				o.put("id", s.getId());
				jsonArr.add(o);
			}
		}
	  }

}